<?php

namespace app\roomcall\controller;

use think\Db;
use Carbon\Carbon;

/**
 * 前台首页控制器
 * @package app\index\controller
 */
class Work extends Home
{
    public $noNeedLogin = [];


    /**
     * 检测当日打卡状态
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function check()
    {
        if ($this->request->isPost()) {
            $userInfo = $this->userInfo;
            $getData = $this->request->post();
            if (empty($getData['time']) || !isset($getData['time'])) {
                $this->result('缺少参数', '', 204);
            }
            $time = explode('-', $getData['time']);
            $week = Carbon::create($time[0], $time[1], $time[2])->dayOfWeekIso;
            //获取用户每天打卡次数
            $workId = Db::name('qt_post_work')->where('post_id', $userInfo['post_id'])->value('work_id');
            $workRes = Db::name('qt_work')->where('id', $workId)->find();
            //查询周一到周日的打卡时间
            $workNum = Db::name('qt_work_num')
                ->where('work_id', $workRes['id'])
                ->where('week', $week)
                ->order('week asc')
                ->group('week')
                ->find();
            //查询今日的打卡次数
            $count = Db::name('qt_work_log')
                ->where(['user_id' => $userInfo['id'], 'group_id' => $userInfo['group_id'], 'day' => $getData['time'], 'week' => $week])
                ->whereIn('type', '1,2,3,5,7,9')
                ->count();
            //正常上班
            if ($workNum['type'] == '1') {
                if ($count == $workRes['work_num']) {
                    $result['status'] = '1'; //打卡正常
                    $result['data'] = []; //打卡正常
                } else {
                    $data = Db::name('qt_work_log')
                        ->field('id,created_time')
                        ->where(['user_id' => $userInfo['id'], 'group_id' => $userInfo['group_id'], 'day' => $getData['time'], 'week' => $week])
                        ->whereIn('type', '0,4')
                        ->select();
                    $result['status'] = '0'; //打卡异常
                    $result['data'] = $data; //打卡异常
                }
            } else {
                //休息日
                $result['status'] = '1'; //打卡正常
                $result['data'] = []; //打卡正常
            }
            $this->result('请求成功', $result, 200);
        }
        $this->result('无效的请求', '', 204);

    }


    /**
     * 统计当前用户昨天的打卡
     */
    public function getyesterday()
    {
        $userInfo = $this->userInfo;
        $time = Carbon::yesterday()->toDateString();
        $week = Carbon::yesterday()->dayOfWeekIso;
        $workConfig = Db::name('qt_work')->where(['group_id' => $userInfo['group_id'], 'post_id' => $userInfo['post_id'], 'status' => '1'])->find();
        if ($workConfig) {
            $work = Db::name('qt_work_num')->where(['work_id' => $workConfig['id'], 'week' => $week])->find();
            if ($work['type'] == '1') {
                $workLog = Db::name('qt_work_log')->where(['user_id' => $userInfo['id'], 'day' => $time])->select();
                foreach ($workLog as $key => $value) {
                    if (empty($value['clock_time']) || $value['type'] == '0') {
                        Db::name('qt_work_log')->where('id', $value['id'])->update(['type' => '4']);
                    }
                }
                //开始时间
                $startRes = Db::name('qt_work_log')->where(['user_id' => $userInfo['id'], 'day' => $time])->order('created_time asc')->find();
                if (empty($startRes['clock_time'])) {
                    $duration = '0';
                } else {
                    $endRes = Db::name('qt_work_log')->where(['user_id' => $userInfo['id'], 'day' => $time])->order('created_time desc')->find();
                    if (empty($endRes['clock_time'])) {
                        $duration = '0';
                    } else {
                        $timeDuration = ($endRes['clock_time'] - $startRes['clock_time']) / 3600;
                        $duration = round($timeDuration, 1);
                    }

                }
                //结束时间
                foreach ($workLog as $key => $value) {
                    if (empty($value['clock_time']) || $value['type'] == '0') {
                        Db::name('qt_work_log')->where('id', $value['id'])->update(['duration' => $duration]);
                    }
                }
            }
        }
    }


    /**
     * 团队用户统计
     */
    public function yesterdayTeam()
    {
        $userInfo = $this->userInfo;
        if ($userInfo['rank' == '1']) {
            $this->result('获取成功', '', 200);
        }
        if ($userInfo['rank' == '3']) {
            $this->result('获取成功', '', 200);
        }
        $time = Carbon::yesterday()->toDateString();
        $week = Carbon::yesterday()->dayOfWeekIso;
        //判断是否存在，如果存在则删除统计
        $find = Db::name('qt_work_team')->where(['user_id' => $userInfo['id'], 'day' => $time, 'type' => '1'])->find();
        if ($find) {
            Db::name('qt_work_team')->where(['id' => $find['id']])->delete();
            Db::name('qt_work_team_log')->where(['work_team_id' => $find['id']])->delete();
        }
        //创建数据
        $pidRes = Db::name('qt_post')->where('post_pid', $userInfo['post_id'])->column('id');
        $userRes = Db::name('qt_users')
            ->alias('u')
            ->leftJoin('qt_post p', 'p.id = u.post_id')
            ->field('u.id,u.nickname')
            ->where('u.team_id', $userInfo['team_id'])
            ->whereIn('p.id', $pidRes)
            ->select();
        //插入用户团队打卡
        $insert['user_id'] = $userInfo['id'];
        $insert['group_id'] = $userInfo['group_id'];
        $insert['week'] = $week;
        $insert['total_num'] = count($userRes);
        $insert['day'] = $time;
        $insert['day'] = $time;
        $insert['day'] = $time;
        $insert['type'] = '1';
        static $late = 0;//迟到
        static $missing = 0;//缺卡
        static $leave = 0;//请假
        static $absenteeism = 0;//旷工
        static $over = 0;//加班
        static $field = 0;//早退
        static $totalDuration = 0;//时长
        $workTeamID = Db::name('qt_work_team')->insertGetId($insert);
        //处理用户打卡记录
        $i = 0;
        foreach ($userRes as $key => $value) {
            $workLog = Db::name('qt_work_log')->where(['day' => $time, 'user_id' => $value['id']])->group('day')->select();
            //开始时间
            $startRes = Db::name('qt_work_log')->where(['user_id' => $userInfo['id'], 'day' => $time])->order('created_time asc')->find();
            if (empty($startRes['clock_time'])) {
                $duration = '0';
            } else {
                $endRes = Db::name('qt_work_log')->where(['user_id' => $userInfo['id'], 'day' => $time])->order('created_time desc')->find();
                if (empty($endRes['clock_time'])) {
                    $duration = '0';
                } else {
                    $timeDuration = ($endRes['clock_time'] - $startRes['clock_time']) / 3600;
                    $duration = round($timeDuration, 1);
                }
            }
            //获取有效的数据
            if ($duration != '0') {
                $i++;
                $totalDuration += $duration;
            }
            foreach ($workLog as $k => $v) {
                //查询迟到
                $chiao = Db::name('qt_work_log')->where(['day' => $v['day'], 'user_id' => $v['user_id'], 'type' => '2'])->find();
                if (!empty($chiao)) {
                    $late += 1;
                    $log['work_team_id'] = $workTeamID;
                    $log['user_id'] = $v['user_id'];
                    $log['time'] = $chiao['clock_time'];
                    $log['type'] = '2';
                    Db::name('qt_work_team_log')->insert($log);
                }
                //缺卡
                $queka = Db::name('qt_work_log')->where(['day' => $v['day'], 'user_id' => $v['user_id'], 'type' => '4'])->find();
                if (!empty($queka)) {
                    $missing += 1;
                    $quekalog['work_team_id'] = $workTeamID;
                    $quekalog['user_id'] = $v['user_id'];
                    $quekalog['time'] = $queka['created_time'];
                    $quekalog['type'] = '4';
                    Db::name('qt_work_team_log')->insert($quekalog);
                }
                //请假
                $qingjia = Db::name('qt_work_log')->where(['day' => $v['day'], 'user_id' => $v['user_id'], 'type' => '9'])->find();
                if (!empty($qingjia)) {
                    $leave += 1;
                    $qingjialog['work_team_id'] = $workTeamID;
                    $qingjialog['user_id'] = $v['user_id'];
                    $qingjialog['time'] = $qingjia['created_time'];
                    $qingjialog['type'] = '9';
                    Db::name('qt_work_team_log')->insert($qingjialog);
                }
                //旷工
                $kuanggong = Db::name('qt_work_log')->where(['day' => $v['day'], 'user_id' => $v['user_id'], 'type' => '6'])->find();
                if (!empty($kuanggong)) {
                    $absenteeism += 1;
                    $kuanggonglog['work_team_id'] = $workTeamID;
                    $kuanggonglog['user_id'] = $v['user_id'];
                    $kuanggonglog['time'] = $kuanggong['created_time'];
                    $kuanggonglog['type'] = '6';
                    Db::name('qt_work_team_log')->insert($kuanggonglog);
                }

                //加班
                $jiaban = Db::name('qt_work_log')->where(['day' => $v['day'], 'user_id' => $v['user_id'], 'type' => '8'])->find();
                if (!empty($jiaban)) {
                    $over += 1;
                    $jiabanlog['work_team_id'] = $workTeamID;
                    $jiabanlog['user_id'] = $v['user_id'];
                    $jiabanlog['time'] = $jiaban['clock_time'];
                    $jiabanlog['type'] = '8';
                    Db::name('qt_work_team_log')->insert($jiabanlog);
                }
                //早退
                $zaotui = Db::name('qt_work_log')->where(['day' => $v['day'], 'user_id' => $v['user_id'], 'type' => '5'])->find();
                if (!empty($zaotui)) {
                    $field += 1;
                    $zaotuilog['work_team_id'] = $workTeamID;
                    $zaotuilog['user_id'] = $v['user_id'];
                    $zaotuilog['time'] = $zaotui['clock_time'];
                    $zaotuilog['type'] = '8';
                    Db::name('qt_work_team_log')->insert($zaotuilog);
                }

            }
        }
        //平均时长
        if ($i != '0') {
            $duration = $totalDuration / $i;
        } else {
            $duration = '0';
        }
        $updata['duration'] = $duration;
        $updata['late'] = $late;
        $updata['missing'] = $missing;
        $updata['leave'] = $leave;
        $updata['absenteeism'] = $absenteeism;
        $updata['over'] = $over;
        $updata['field'] = $field;
        $up = Db::name('qt_work_team')->where(['id' => $workTeamID])->update($updata);
        if ($up) {
            $this->result('获取昨日团队数据成功', '', 200);
        }
        $this->result('获取失败', '', 204);
    }


    /**
     * 获取用户打卡时间
     */
    public function work_config()
    {
        if ($this->request->isGet()) {
            //打卡位置
            $userInfo = $this->userInfo;
            $this->getyesterday();
            $resData['address'] = Db::name('qt_work_config')->field('address,lat,lon,distance')->where('status', '1')->where('group_id', $userInfo['team_id'])->find();
            $resData['group'] = Db::name('qt_group')->where('id', $userInfo['team_id'])->value('name');
            //打卡时间
            $week = Carbon::now()->dayOfWeekIso;//星期
            $day = Carbon::now()->toDateString();
            $workId = Db::name('qt_post_work')->where('post_id', $userInfo['post_id'])->value('work_id');
            $workConfig = Db::name('qt_work')->where(['id' => $workId, 'status' => '1'])->find();
            if (empty($workConfig)) {
                $this->result('暂时无法获取打卡时间，请联系管理员', '', 204);
            }
            //将打卡时间插入打卡记录
            $time = Db::name('qt_work_num')->where(['work_id' => $workConfig['id'], 'week' => $week])->order('start_time asc')->select();
            $find = Db::name('qt_work_log')->where(['user_id' => $userInfo['id'], 'group_id' => $userInfo['group_id'], 'day' => $day])->find();
            if (!$find) {
                foreach ($time as $key => $value) {
                    $userInfo = $this->userInfo;
                    $insertData = $this->getData($userInfo, $value);
                    Db::name('qt_work_log')->insertAll($insertData);
                }
            }
            //当前时间与打卡时间进行比对
            //查询最近的打卡时间
            $startWork = Db::name('qt_work_log')
                ->field('id,clock_time,type,day,work_time_id,work_type')
                ->where('created_time', '>=', time())
                ->where(['user_id' => $userInfo['id'], 'group_id' => $userInfo['group_id'], 'day' => $day])
                ->order('created_time asc')
                ->find();
            if (empty($startWork)) {
                $startWork = Db::name('qt_work_log')
                    ->field('id,clock_time,type,day,work_time_id,work_type')
                    ->where('created_time', '<=', time())
                    ->where(['user_id' => $userInfo['id'], 'group_id' => $userInfo['group_id'], 'day' => $day])
                    ->order('created_time desc')
                    ->find();
            }
            $workRes = Db::name('qt_work_num')
                ->field('wn.start_time,wn.end_time,wn.type')
                ->alias('wn')
                ->leftJoin('qt_work w', 'wn.work_id = w.id')
                ->where('wn.id', $startWork['work_time_id'])
                ->find();
            //如果上班类型为下班卡查找上班卡的状态
            if ($startWork['work_type'] == '2') {
                $morning = Db::name('qt_work_log')
                    ->field('id,clock_time,type,day,work_time_id,work_type')
                    ->where(['user_id' => $userInfo['id'], 'day' => $startWork['day'], 'work_time_id' => $startWork['work_time_id'], 'work_type' => '1'])
                    ->find();
                $afternoon = $startWork;
            } else {
                $afternoon = Db::name('qt_work_log')
                    ->field('id,clock_time,type,day,work_time_id,work_type')
                    ->where(['user_id' => $userInfo['id'], 'day' => $startWork['day'], 'work_time_id' => $startWork['work_time_id'], 'work_type' => '2'])
                    ->find();
                $morning = $startWork;
            }
            $resData['work'] = $workRes;
            $resData['morning'] = $morning;
            $resData['afternoon'] = $afternoon;
            $resData['status'] = $startWork['work_type'];
            $resData['late'] = $workConfig['late'];
            $this->result('获取11111成功', $resData, 200);
        }
    }


    /**
     * 打卡
     */
    public function clock()
    {
        if ($this->request->isPost()) {
            //打卡位置
            $getData = $this->request->post();
            if (empty($getData['clock_id']) || empty($getData['lat']) || empty($getData['lon'])) {
                $this->result('缺少参数', '', 204);
            }
            //查找当前的打卡信息
            $find = Db::name('qt_work_log')->where('id', $getData['clock_id'])->find();
            //可以迟到的时间
            $late = Db::name('qt_work')->where('id', $find['work_id'])->value('late');
            //上班卡
            if ($find['work_type'] == '1') {
                $creat_time = $find['created_time'] + ($late * 60);
                $nowTime = time();
                if ($nowTime <= $creat_time) {
                    $type = '1';
                } else {
                    $type = '2';
                }
            }
            //下班卡
            if ($find['work_type'] == '2') {
                $creat_time = $find['created_time'];
                $nowTime = time();
                if ($nowTime <= $creat_time) {
                    $type = '5';
                } else {
                    $type = '1';
                }
            }
            $save = Db::name('qt_work_log')->where('id', $getData['clock_id'])
                ->update(['type' => $type, 'clock_time' => $nowTime, 'lon' => $getData['lon'], 'lat' => $getData['lat']]);
            if ($save) {
                $this->result('打卡成功', '', 200);
            }
            $this->result('打卡失败', '', 204);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 考勤打卡说明
     */
    public function explain()
    {
        if ($this->request->isGet()) {
            //打卡位置
            $userInfo = $this->userInfo;
            $data = Db::name('qt_work')
                ->alias('w')
                ->field('w.time_rule,w.work_rule,w.repair_rule,wc.address,wc.distance')
                ->leftJoin('qt_work_config wc', 'wc.group_id = w.group_id')
                ->where(['w.group_id' => $userInfo['group_id'], 'w.post_id' => $userInfo['post_id']])
                ->find();
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * @param $data
     */
    public function getData($userInfo, $data)
    {
        $week = Carbon::now()->dayOfWeekIso;//星期
        //$day = Carbon::now()->toDateString();
        $day = strtotime(date('Y-m-d', time()));
        $startTime = $day . ' ' . $data['start_time'];
        $startTime = strtotime($startTime);
        $endTime = $day . ' ' . $data['end_time'];
        $endTime = strtotime($endTime);
        $insertData[0]['user_id'] = $userInfo['id'];
        $insertData[0]['group_id'] = $userInfo['group_id'];
        $insertData[0]['work_id'] = $data['work_id'];
        $insertData[0]['work_time_id'] = $data['id'];
        $insertData[0]['week'] = $week;
        $insertData[0]['day'] = $day;
        $insertData[0]['work_type'] = '1';
        $insertData[0]['created_time'] = $startTime;
        $insertData[0]['type'] = '0';
        $insertData[1]['user_id'] = $userInfo['id'];
        $insertData[1]['group_id'] = $userInfo['group_id'];
        $insertData[1]['work_id'] = $data['work_id'];
        $insertData[1]['work_time_id'] = $data['id'];
        $insertData[1]['week'] = $week;
        $insertData[1]['day'] = $day;
        $insertData[1]['work_type'] = '2';
        $insertData[1]['created_time'] = $endTime;
        $insertData[1]['type'] = '0';
        return $insertData;
    }

    /**
     * 获取无线网数据列表
     */
    public function wifiList()
    {
        if ($this->request->isPost()) {
            $userInfo = $this->userInfo;
            $data = Db::name('qt_store_wifi')
                ->field('id,wifi,mac')
                ->where(['store_id' => $userInfo['store_id']])
                ->select();
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 获取无线网数据列表
     */
    public function wifiAdd()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (!isset($getData['wifi']) || empty($getData['wifi'])) {
                $this->result('缺少参数', '', 204);
            }
            if (!isset($getData['mac']) || empty($getData['mac'])) {
                $this->result('缺少参数', '', 204);
            }
            $getData['created_time'] = time();
            $getData['store_id'] = $this->userInfo['store_id'];
            $data = Db::name('qt_store_wifi')->insert($getData);
            if ($data) {
                $this->result('添加成功', '', 200);
            }
            $this->result('添加失败', '', 204);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 获取无线网数据列表
     */
    public function wifiDel()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (!isset($getData['id']) || empty($getData['id'])) {
                $this->result('缺少参数', '', 204);
            }
            $del = Db::name('qt_store_wifi')->where('id', $getData['id'])->delete();
            if ($del) {
                $this->result('删除成功', '', 200);
            }
            $this->result('删除失败', '', 204);
        }
        $this->result('无效的请求', '', 204);
    }


}
